#!/usr/bin/python

import os
import sys
import datetime
import urllib
import re
from optparse import OptionParser

from yahoo.search.web import WebSearch
from movie.vote.models import Movie


class YoutubeTrailerFinder(object):
  def __init__(self, movie_name):
    self.movie_name = movie_name

  def FindTrailerUrl(self):
    srch = WebSearch(app_id='YahooDemo')
    srch.query = '%s trailer site:youtube.com' % (self.movie_name,)
    srch.results = 1
    print 'query was: %s' % (srch.query,)
    for x in srch.parse_results():
      return x.Url
    return None


def UpdateMovieTrailers(days_back):
  if not days_back:
    movies = Movie.objects.all()
  else:
    cutoff = datetime.datetime.now() - datetime.timedelta(days_back)
    movies = Movie.objects.filter(date_added__gt=cutoff)
  for movie in movies:
    if movie.youtube_trailer_url:
      continue
    yt = YoutubeTrailerFinder(movie.name).FindTrailerUrl()
    if not yt:
      continue
    print 'Adding trailer for %s: %s' % (movie.name, yt)
    movie.youtube_trailer_url = yt
    movie.save()
  

if __name__ == '__main__':
  usage = "usage: %prog [options]"
  parser = OptionParser(usage)
  parser.add_option('-d', '--days_back', type='int', dest='days_back', default=5,
                    help='skip movies older than this many days')
  (options, args) = parser.parse_args()
  UpdateMovieTrailers(days_back=options.days_back)
